function generate_a(class_name, url, text) {
  a = '<a class="' + class_name + '" href="'+ 
  url + '">' + text + '</a>';
  return a;
}

function generate_span(class_name, text) {
  a = '<span class="' + class_name + '">' + 
  text + '</span>';
  return a;
}

function generate_ad(google_ad) {
  title = generate_a("ad_title", google_ad.url, google_ad.line1);
  text = generate_span("ad_text", google_ad.line2 + " " + google_ad.line3);
  url = generate_a("ad_url", google_ad.url, google_ad.visible_url);
  ad = '<div class="ad">' + title + "<br>" + text + "<br>" + url + '</div>';
  return ad;
}

function generate_ad_blocks(google_ads, block_array) {
  var result=[]
  var current_ad=0
  var total_ads=google_ads.length;
  
  for (var i=0; i <= block_array.length; i++) {
    for (var j=1; j <= block_array[i]; j++) {
      //alert(current_ad+","+total_ads+","+i+","+j+","+google_ads[current_ad]);
      if (result[i]) {
        result[i] += generate_ad(google_ads[current_ad]);
      }
      else {
        result[i] = generate_ad(google_ads[current_ad]);
      }
      current_ad += 1;
      if (current_ad >= total_ads) {
        return result;
      }
    }
  }
}

function google_ad_request_done(google_ads) { 
  /* 
  * This function is required and is used to display 
  * the ads that are returned from the JavaScript 
  * request. You should modify the document.write 
  * commands so that the HTML they write out fits 
  * with your desired ad layout. 
  */ 
  var s;
  /* 
  * Verify that there are actually ads to display. 
  */ 
  if (google_ads.length == 0) 
  return; 
  s = generate_a("ad_attribution", google_info.feedback_url, "Ads by Google");
  if (google_ads[0].type == "text") { 
    var ad_blocks = generate_ad_blocks(google_ads, gwo_block_array);
    for (var i=0; i <= ad_blocks.length; i++) {
      ad_block = '<div id="' + gwo_style + '">';
      ad_block += '<div class="attribution">' + s + '</div>'; 
      ad_block += ad_blocks[i] + '</div>';
      $(gwo_block_ids[i]).append(ad_block);
    }
  } 
  return; 
}
